package com.chunxuan.langquan.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.NewOrderInfo;
import com.chunxuan.langquan.dao.bean.OrderBottomBean;
import com.chunxuan.langquan.dao.bean.OrderInfo;
import com.chunxuan.langquan.dao.bean.ProductBean;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.support.util.SpacesItemDecoration;
import com.chunxuan.langquan.ui.adapter.MyOrderListAdapter;
import com.google.gson.Gson;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.reactivex.functions.Consumer;

public class MyOrder1Fragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {
    private RecyclerView rcv_list;// 我的订单列表
    private LinearLayout llEmptyOrder;

    private MyOrderListAdapter adapter;
    private List<OrderInfo> orderList = new ArrayList<>();
    private int type = 0;
    private String orderNum;// 订单号
    private List<Object> mAllOrderList = new ArrayList<>();
    private SmartRefreshLayout vRefresh;
    private int mPage = 1, mPageSize = 10;
    public MyOrder1Fragment() {

    }

    public static MyOrder1Fragment newInstance(String type) {
        MyOrder1Fragment fragment = new MyOrder1Fragment();
        Bundle args = new Bundle();
//        args.putString("type", type);
        args.putInt("type", Integer.parseInt(type));
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments().getInt("type");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_my_order1, container, false);
        rcv_list = v.findViewById(R.id.rcv_list);
        llEmptyOrder = v.findViewById(R.id.ll_empty_order);

        vRefresh = v.findViewById(R.id.vRefresh);
        adapter = new MyOrderListAdapter(getActivity(),mAllOrderList);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_list.setLayoutManager(manager);
        rcv_list.setAdapter(adapter);
//        EventBus.getDefault().register(this);

        vRefresh.setOnRefreshListener(this);
        vRefresh.setOnLoadMoreListener(this);
        vRefresh.autoRefresh();

        return v;

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        APIRetrofit.getDefault().getOrders(Global.HEADER, type, mPage, mPageSize)
                .compose(RxUtil.<BaseResult2<List<OrderInfo>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<OrderInfo>>>() {
                    @Override
                    public void accept(BaseResult2<List<OrderInfo>> listBaseResult2) throws Exception {
                        hideProgress();
                        vRefresh.finishRefresh();
                        vRefresh.finishLoadMore();
                        if (listBaseResult2.isSuccess()) {
                            mPage++;
                            orderList.addAll(listBaseResult2.getData());
                            if(null!=orderList&&orderList.size()>0){

                                List<Object> list = handleList(orderList);


//                                int index=0;
//                                List<NewOrderInfo> newOrderInfoList=new ArrayList<>();
//                                List<ProductBean> products=new ArrayList<>();
//                                for(int t=0;t<orderList.size();t++){
//                                    if(orderList.get(t).getProducts()!=null&&orderList.get(t).getProducts().size()>0){
//                                        newOrderInfoList.add(new NewOrderInfo(1,orderList.get(t).getProducts(),null));
//                                    }
//                                    OrderBottomBean orderBottomBean=new OrderBottomBean();
//                                    orderBottomBean.setHave_paid(orderList.get(t).getHave_paid());
//                                    orderBottomBean.setHave_received(orderList.get(t).getHave_received());
//                                    orderBottomBean.setOrder_id(orderList.get(t).getOrder_id());
//                                    orderBottomBean.setOut_trade_no(orderList.get(t).getOut_trade_no());
//                                    orderBottomBean.setState(orderList.get(t).getState());
//                                    orderBottomBean.setStatus(orderList.get(t).getStatus());
//                                    orderBottomBean.setTotal_price(orderList.get(t).getTotal_price());
//                                    orderBottomBean.setRefund_status_text(orderList.get(t).getRefund_status_text());
//                                    if(orderList.get(t).getProducts()!=null&&orderList.get(t).getProducts().size()>0){
//                                        orderBottomBean.setOrder_product_id(orderList.get(t).getProducts().get(0).getOrder_product_id());
//                                    }
//
//                                    if(orderList.get(t).getProducts()!=null){
//                                        orderBottomBean.setTotal_num(orderList.get(t).getProducts().size());
//                                    }
//                                    newOrderInfoList.add(new NewOrderInfo(2,orderList.get(t).getProducts(),orderBottomBean));
//                                }
                                adapter.addData(list);
                            }
                            adapter.notifyDataSetChanged();
                        }
//                        if (listBaseResult2.isSuccess()) {
//                            mPage++;
//                            orderList.addAll(listBaseResult2.getData());
//                            if(null!=orderList&&orderList.size()>0){
//                                int index=0;
//                                for(int t=0;t<orderList.size();t++){
//                                    if(orderList.get(t).getProducts()!=null&&orderList.get(t).getProducts().size()>0){
//                                        if(orderList.get(t).getProducts().size()>1){
//                                            rcv_list.addItemDecoration(new SpacesItemDecoration(-45));
//                                        }
//                                        if(index==0){
//                                            index+=orderList.get(t).getProducts().size();
//                                            adapter.addBottom(index,orderList.get(0));
//                                        }else{
//                                            index+=orderList.get(t).getProducts().size()+1;
//                                            adapter.addBottom(index,orderList.get(t));
//                                        }
//                                    }
//                                }
//                            }
//                            adapter.notifyDataSetChanged();
//                        }
                        if (mPage == 1 && isDataEmpty(orderList)) {
                            llEmptyOrder.setVisibility(View.VISIBLE);
                        } else if (isDataEmpty(orderList)) {
                            vRefresh.setEnableLoadMore(false);
                        } else {
                            llEmptyOrder.setVisibility(View.GONE);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        llEmptyOrder.setVisibility(View.VISIBLE);
                    }
                });
    }

    private List<Object> handleList(List<OrderInfo> resultList) {
        List<Object> dataList = new ArrayList<Object>();
        for(OrderInfo orderSummary:resultList){
            OrderBottomBean orderBottomBean=new OrderBottomBean();
            orderBottomBean.setHave_paid(orderSummary.getHave_paid());
            orderBottomBean.setHave_received(orderSummary.getHave_received());
            orderBottomBean.setOrder_id(orderSummary.getOrder_id());
            orderBottomBean.setOut_trade_no(orderSummary.getOut_trade_no());
            orderBottomBean.setState(orderSummary.getState());
            orderBottomBean.setStatus(orderSummary.getStatus());
            orderBottomBean.setTotal_price(orderSummary.getTotal_price());
            orderBottomBean.setRefund_status_text(orderSummary.getRefund_status_text());
            if(orderSummary.getProducts()!=null&&orderSummary.getProducts().size()>0){
                orderBottomBean.setOrder_product_id(orderSummary.getProducts().get(0).getOrder_product_id());
            }
            if(orderSummary.getProducts()!=null){
                orderBottomBean.setTotal_num(orderSummary.getProducts().size());
            }
            List<ProductBean> orderDetailList=orderSummary.getProducts();
            HashMap<Object, List<ProductBean>> orderGoodsMap=new HashMap<>();
            for(ProductBean orderGoodsItem : orderDetailList){
                int orderCode=orderGoodsItem.getOrder_product_id();
                List<ProductBean> goodsList=orderGoodsMap.get(orderCode);
                if(null==goodsList){
                    goodsList=new ArrayList<>();
                    orderGoodsMap.put(orderCode, goodsList);
                }
                goodsList.add(orderGoodsItem);
            }
            Set<Object> keySet = orderGoodsMap.keySet();
            for(Object orderCode : keySet) {
                dataList.addAll(orderGoodsMap.get(orderCode));
            }
            dataList.add(orderBottomBean);
        }
        return dataList;
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        orderList.clear();
        adapter.notifyDataSetChanged();
        vRefresh.setEnableLoadMore(true);
        mPage = 1;
        onLoadMore(refreshLayout);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        onRefresh(vRefresh);
    }
}
